#include "server.h"
#define PORT (8081)

Server::Server(QObject *parent)
    : QObject(parent)
    ,tcpserver(new QTcpServer(this))
{
    connect(tcpserver,&QTcpServer::newConnection,this,&Server::handleTOConnect);
    //初始化
    init();
}


void Server::initSql()
{
    sqldb = QSqlDatabase::addDatabase("QMYSQL");
    sqldb.setHostName("127.0.0.1");
    sqldb.setDatabaseName("chat_system");
    sqldb.setPort(3306);
    sqldb.setUserName("root");
    sqldb.setPassword("123sushanshan");

    if(!sqldb.open())
    {
        emit logInfoMessage(Log::MessageType::Error,"数据库打开失败: "+sqldb.lastError().text());
        return ;
    }

    emit logInfoMessage(Log::MessageType::Info, "数据库连接成功！");

    QString sqluser = "CREATE TABLE IF NOT EXISTS users(id INT PRIMARY KEY AUTO_INCREMENT,"
                      "username VARCHAR(50) UNIQUE NOT NULL,"
                      "password VARCHAR(20) NOT NULL)";

//    QString sqlmessage = "CREATE TABLE IF NOT EXISTS users(id INT PRIMARY KEY AUTO_INCREMENT,"
//                      "username VARCHAR(50) UNIQUE NOT NULL,"
//                      "password VARCHAR(20) NOT NULL)";
    QSqlQuery sql;
    if(!sql.exec(sqluser))
    {
        emit logInfoMessage(Log::MessageType::Warning,"执行创建users表语句失败:" + sql.lastError().text());
    }
    else
    {
        emit logInfoMessage(Log::MessageType::Info,"创建表users表成功!");
    }
    qDebug() << "Available drivers: " << QSqlDatabase::drivers()<<endl;
}

void Server::init()
{
    //初始化数据库
    initSql();

    //启动服务器 开始监听
    startserver();

}

Server::~Server()
{

}

void Server::startserver()
{
    QHostAddress address = QHostAddress::Any;

    if(!tcpserver->listen(address,(PORT)))
    {
        emit logInfoMessage(Log::MessageType::Error,tcpserver->errorString());
    }
    else
    {
        //日志
        //qDebug()<<"服务器监听成功"<<endl;
        emit logInfoMessage(Log::MessageType::Info,"服务器监听成功，端口号:"+QString::number(PORT));
    }
}

void Server::handleTOConnect()
{
    QTcpSocket* clientsocket = tcpserver->nextPendingConnection();

    connect(clientsocket,&QTcpSocket::readyRead,this,&Server::handleTORead);

    //后面可以启动线程处理
    if(clientsocket)
    {
        QString clientIP = clientsocket->peerAddress().toString();
        quint16 clientPort = clientsocket->peerPort();

        if (clientIP.startsWith("::ffff:")) {
            clientIP = clientIP.mid(7); // 截取 "::ffff:" 之后的部分
        }

        emit logInfoMessage(Log::MessageType::Info,QString("新的客户端连接: IP:%1 port:%2").arg(clientIP).arg(clientPort));
    }
    else
    {
        emit logInfoMessage(Log::MessageType::Warning, "收到连接通知，但无法获取客户端套接字");
    }
}

void Server::handleTORead()
{
    QTcpSocket* client = qobject_cast<QTcpSocket*>(sender());

    while(client->canReadLine())
    {
        QByteArray data = client->readLine().trimmed();

        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(data,&error);
        if(error.error != QJsonParseError::NoError)
        {
            emit logInfoMessage(Log::MessageType::Error,QString("Json串解析失败:"+error.errorString()));
            return;
        }

        QJsonObject clientjson = doc.object();
        int type = clientjson["MessageType"].toInt();
        QString username = clientjson["username"].toString();
        QString password = clientjson["password"].toString();
        //根据消息类型处理
        switch (type)
        {
            case 1:
                handleLogin(client,clientjson);
                break;
            case 2:
                handleChat(client,clientjson);
                break;
            case 3:
                handleServerBroadcast(client,clientjson);
                break;
            case 4:
                handleRegiste(client,clientjson);
                break;
        default:
            emit logInfoMessage(Log::MessageType::Warning,"客户端发送消息类型错误"+ QString::number(type));
            break;

        }
    }

    //判断登录信息
    //emit logInfoMessage(MessageType::Info,username+" "+password+" "+QString::number(type));
}



void Server::handleLogin(QTcpSocket *socket, QJsonObject &doc)
{
    if (!sqldb.isOpen()) {
        emit logInfoMessage(Log::MessageType::Error, "数据库未打开！");
        return;
    }
    QString username = doc["username"].toString();
    QString password = doc["password"].toString();

    QSqlQuery sqlquery;
    sqlquery.prepare("SELECT EXISTS(SELECT 1 from users where username = :username AND password = :password) ");
    sqlquery.bindValue(":username",username);
    sqlquery.bindValue(":password",password);

    QJsonObject ret;
    ret["username"] = username;
    if(sqlquery.exec() && sqlquery.next())
    {
        bool isexists;
        isexists = sqlquery.value(0).toBool();
        //判断数据库中是否有用户输入的用户名密码信息
        //使用套接字通知验证结果
        ret["success"] = isexists;
        if(isexists)
        {
            ret["message"] = "登录成功";
            emit logInfoMessage(Log::MessageType::Info, username + " 登录成功！");
        }
        else
        {
            ret["message"] = "用户名或密码错误";
            emit logInfoMessage(Log::MessageType::Warning, username + " 登录失败！");
        }

    }
    else
    {
        ret["success"] = false;
        ret["message"] = "数据库查询失败";
        emit logInfoMessage(Log::MessageType::Error, "SQL执行失败: " + sqlquery.lastError().text());
    }
    sendjson(socket,Protocol::ResponseType::Res_Login,ret);
}

//服务器向客户端发送信息
void Server::sendjson(QTcpSocket *socket, Protocol::ResponseType type, QJsonObject &data)
{
    QJsonObject sendjson = data;
    sendjson["MessageType"] = static_cast<int>(type);

    QJsonDocument doc(sendjson);
    //传输到tcp发送缓冲区
    QByteArray array =  doc.toJson(QJsonDocument::Compact);
    array.append('\n');
    socket->write(array);
}

void Server::handleChat(QTcpSocket *socket, QJsonObject &doc)
{

}

void Server::handleServerBroadcast(QTcpSocket *socket, QJsonObject &doc)
{

}

void Server::handleRegiste(QTcpSocket *socket, QJsonObject &doc)
{
    if (!sqldb.isOpen()) {
        emit logInfoMessage(Log::MessageType::Error, "数据库未打开！");
        return;
    }
    QString username = doc["username"].toString();
    QString password = doc["password"].toString();


    QSqlQuery sqlquery;
    sqlquery.prepare("INSERT INTO  users(username,password) VALUES(:username,:password)");
    sqlquery.bindValue(":username",username);
    sqlquery.bindValue(":password",password);

    QJsonObject ret;
    ret["username"] = username;

    QSqlQuery checkQuery;
    checkQuery.prepare("SELECT COUNT(*) FROM users WHERE username = :username");
    checkQuery.bindValue(":username", username);
    if (checkQuery.exec() && checkQuery.next()) {
        int count = checkQuery.value(0).toInt();
        if (count > 0) {
            ret["success"] = false;
            ret["message"] = "用户名已存在";
            sendjson(socket, Protocol::ResponseType::Res_Registe, ret);
            return;
        }
    }


    if (!sqlquery.exec()) {
        ret["success"] = false;
        ret["message"] = "数据库查询失败";
        emit logInfoMessage(Log::MessageType::Error, "SQL执行失败: " + sqlquery.lastError().text());
        sendjson(socket,Protocol::ResponseType::Res_Registe,ret);
        return ;
    }

    ret["success"] = true;
    ret["message"] = "注册成功";
    emit logInfoMessage(Log::MessageType::Info, username + " 注册成功！");

    sendjson(socket,Protocol::ResponseType::Res_Registe,ret);

}


